#pragma once
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <functional>

void PrintLog()
{
    std::cout << "我是一个打印日志的任务" << std::endl;
}

void DownLoad()
{
    std::cout << "我是一个下载任务" << std::endl;
}

void UpLoad()
{
    std::cout << "我是一个上传任务" << std::endl;
}

typedef void(*task_function)();

class TaskManager
{
public:
    TaskManager()
    {
        srand(time(0));
    };

    void Register(task_function func)
    {
        _tasks.push_back(func);
    }

    int Code()
    {
        return rand() % _tasks.size();
    }

    void Execute(int code)
    {
        if(code > 0 && code < _tasks.size())
        _tasks[code]();
    }
private:
    std::vector<task_function> _tasks;
};

class Channel
{
public:
    Channel(int wfd, pid_t subid)
        : _wfd(wfd)
        , _subid(subid)
    {
        _name = "child name is" + std::to_string(_wfd) + "//" + std::to_string(_subid);
    }

    void Close()
    {
        close(_wfd);
    }

    void Wait()
    {
        waitpid(_subid, nullptr, 0);
    }

    void Send(int taskcode)
    {
        write(_wfd, &taskcode, sizeof(taskcode));
    }

    int Fd(){return _wfd;}
    pid_t Subid(){return _subid;}
    std::string Name(){return _name; }

    ~Channel(){}
private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};

class ChannelManager
{
public:
    ChannelManager()
        : _next(0)
    {};

    void Insert(int wfd, pid_t subid)
    {
        _channels.emplace_back(wfd, subid);
    }

    void StopProcess()
    {
        for(auto& e : _channels)
        {
            e.Close();
            std::cout << "已关闭子进程" << e.Subid() << std::endl;
        }
    }

    void WaitProcess()
    {
        for(auto& e : _channels)
        {
            e.Wait();
            std::cout << "已等待成功子进程" << e.Subid() << std::endl;
        }
    }

    Channel& Select()
    {
        auto& c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }

    ~ChannelManager(){};
private:
    std::vector<Channel> _channels;
    int _next;
};

//默认进程池中进程的数目
#define DEFAULTNUM 5

class ProcessPool
{
public:
    ProcessPool()
    {
        _tm.Register(DownLoad);
        _tm.Register(UpLoad);
        _tm.Register(PrintLog);
    }

    void Work(int rfd)
    {
        while(1)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if(n > 0)
            {
                if(n != sizeof(code))
                {
                    continue;
                }
                std::cout << "子进程" << getpid() << "收到一份任务码" << code << std::endl;
                _tm.Execute(code);
            }
            else if(n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "读取失败" << std::endl;
                break;
            }
        }
    }

    bool Create(int num)
    {
        for(int i = 0; i < num; i++)
        {
            //创建管道
            int pipefds[2] = {0};
            int n = pipe(pipefds);
            if(n < 0)
            {
                return false;
            }
            //创建子进程
            pid_t id = fork();
            if(id == 0)
            {
                //子进程
                close(pipefds[1]);
                //std::cout << pipefds[0] << pipefds[1] << std::endl;
                Work(pipefds[0]);
                close(pipefds[0]);
                exit(0);
            }
            else
            {
                //父进程
                close(pipefds[0]);
                //这里还不能关闭pipefds[1]，因为后续还有父进程写入操作
                _cm.Insert(pipefds[1], id);
            }
        }
        return true;
    }

    void Run()
    {
        //获取任务码
        int taskcode = _tm.Code();

        //选择一个合适的进程
        auto& c = _cm.Select();
        std::cout << "选择了一个进程:" << c.Name() << std::endl;

        c.Send(taskcode);
        std::cout << "发送了任务码" << taskcode << std::endl;
    }

    void Stop()
    {
        _cm.StopProcess();
        _cm.WaitProcess();
    }

    ~ProcessPool(){}
private:
    ChannelManager _cm;
    TaskManager _tm;
};